package com.gitee.beiding.cloud.base.handler;

import com.gitee.beiding.cloud.base.standard.R;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Component
public class ValidExceptionHandler {

    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.OK)
    public R handlerException(BindException e) {
        return R.error(extractErrorMsg(e.getBindingResult()));
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public R handlerException(Exception e) {
        return R.error(e.getMessage());
    }

    private String extractErrorMsg(BindingResult result) {
        List<FieldError> errors = result.getFieldErrors();
        return errors.stream().map(e -> e.getField() + ":" + e.getDefaultMessage())
                .reduce((s1, s2) -> s1 + " ; " + s2).orElse("参数非法");
    }
}
